//
// Created by LiuYou on 2021/10/29.
//

#include <iostream>
#include <cstring>
#include <unistd.h>
#include <csignal>


static const int THREAD_NUM = 4;

static pthread_t tidArray[THREAD_NUM];

static bool isLoop = true;


int main(int argc, char** argv) {

    struct sigaction sa{};
//    sa.sa_handler = alarmHandler;
    // 注意: 调用 pthread_cancel();后程序还是不能正常退出。
//    sa.sa_handler = [](int signal) {
//        for (int i = 0; i < THREAD_NUM; ++i) {
//            pthread_cancel( tidArray[i] );
//        }
//    };
    // 而这种设计就可以正常退出。
    sa.sa_handler = [](int signal) {
        isLoop = false;
    };
    sa.sa_flags = 0;
    sigemptyset( &sa.sa_mask );

    sigaction( SIGALRM, &sa, nullptr );
    alarm( 5 );

//    pthread_t tidArray[THREAD_NUM]{};
    for (int i = 0; i < THREAD_NUM; ++i) {
        int* pInt = new int( i );
        int errNum = pthread_create(
                tidArray + i, nullptr,
                [](void* args) -> void* {

//                    int ch = 'a' + *static_cast<char*>(args);
                    int ch = 'a' + *(int*) args;
                    char buf[10]{};
                    snprintf( buf, 10, "%c", ch );


                    while (isLoop) {
//                        write( STDOUT_FILENO, &ch, 1 );
                        write( STDOUT_FILENO, buf, 1 );
                    }

                    pthread_exit( args );
                },
                pInt );
        if (errNum != 0) {
            fprintf( stderr, "pthread_create(): %s.\n", strerror( errNum ));
            return 1;
        }
    }

    for (int i = 0; i < THREAD_NUM; ++i) {
        void* threadReturn{};
        pthread_join( tidArray[i], &threadReturn );
        delete static_cast<int*>(threadReturn);
    }


    return 0;
}
